import { BrowserRouter, Routes, Route, useLocation, Navigate } from 'react-router-dom'
import Page from './page'
import {RouterType} from '../interface'
import { getCookie } from '../utils'


const Router = () => {

    const BeforeEach = (props:any) => {

        const location = useLocation()

        // 路由拦截 
        // 判断 当前浏览器中是否存在cookie 如果不存在 并且 即将要进入的路由 不是登录页面的话 就让其跳转到登录页面
        if(!getCookie() && location.pathname !== '/login') {
            return <Navigate to='/login' />
        }

        // 否则 就让其正常跳转
        return props.children
    }


    const renderRouter = (routes:RouterType[]) => {
        return routes.map((item:RouterType, idx: number) => {
            return <Route key={idx} path={item.path} element={<BeforeEach> {item.element} </BeforeEach>} >
                {
                    item.children && renderRouter(item.children)
                }
            </Route>
        })
     }

    return <BrowserRouter>
        <Routes>
            {
                renderRouter(Page)
            }
        </Routes>
    </BrowserRouter>
}

export default Router
